<template>
    <div style="width: 100%;">
        <TitleTips :title="title" />
        <el-form ref="form" :model="form" class="size-auto width-100" :rules="rules" :inline="true" size="medium" :label-width="labelWidth">
            <CardBox v-for="(item, index) in form[listName]" :key="item.uid" :title="`序号${index + 1}`">
                <BaseButton v-if="form[listName].length > 1" slot="button" type="text" color="danger" icon="el-icon-delete" @click="handleDelete(index)">删除</BaseButton>
                <el-row :gutter="24">
                    <!-- formItems里是每一项的配置：code为绑定的key，type为类型，name为中文名，unit为带单位的 -->
                    <el-col v-for="m in formItems" :key="m.code" :lg="m.type === 'textarea' ? 24 : 8" :xl="m.type === 'textarea' ? 24 : 6">
                        <el-form-item v-if="m.type === 'input'" :label="m.name" :prop="`${listName}.${index}.${m.code}`" :rules="rules[m.code]">
                            <el-input v-model.trim="form[listName][index][m.code]" maxlength="50" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                        <el-form-item v-if="m.type === 'number'" :label="m.name" :prop="listName + '.' + index + '.' + m.code" :rules="rules[m.code]">
                            <el-input v-model.trim="form[listName][index][m.code]" :disabled="m.disabled" clearable placeholder="支持小数点后2位" @change="handleComputed(index, m.event)">
                                <i v-if="m.unit" slot="suffix" class="el-input__icon input-unit">{{ m.unit === true ? form[listName][index]['arithmeticalUnit'] : m.unit }}</i>
                            </el-input>
                        </el-form-item>
                        <el-form-item v-if="m.type === 'textarea'" :label="m.name" class="margin-r-0 block-item">
                            <el-input v-model.trim="form[listName][index][m.code]" type="textarea" maxlength="200" show-word-limit clearable placeholder="请输入" />
                        </el-form-item>
                        <el-form-item v-if="m.type === 'spe'" :class="{'is-error': isError[index]}" :label="m.name">
                            <el-input v-model="form[listName][index]['prepareCompletionMoney']" maxlength="15" :disabled="m.disabled" @change="(val)=>(validMoney(val, form[listName][index]['budgetMoney'], index))">
                                <i slot="suffix" class="el-input__icon input-unit">元</i>
                            </el-input>
                            <!-- 自定义错误验证信息 -->
                            <div v-if="isError[index]" class="el-form-item__error">计划完成金额不能超出预算金额</div>
                        </el-form-item>
                        <el-form-item v-if="m.type === 'select'" :label="m.name" :prop="`${listName}.${index}.${m.code}`" :rules="rules[m.code]">
                            <el-select
                                v-model="form[listName][index][m.code]"
                                :disabled="m.disabled"
                                :multiple="m.multiple"
                                :placeholder="m.placeholder"
                                style="width: 100%;"
                                @change="(val) => (handleBackfill(index, val, m.code))"
                            >
                                <el-option
                                    v-for="option in m.options"
                                    :key="option.uid"
                                    :label="option.label"
                                    :value="option.value"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </CardBox>
        </el-form>
        <div class="add-box" @click="addCard">
            <span>
                <i class="el-icon-plus" />
                <i>添加</i>
            </span>
        </div>
    </div>
</template>

<script>
import reconfirm from '@/utils/reconfirm'
import { uniqueId } from 'lodash-es'
import BigNumber from 'bignumber.js'

export default {
    name: 'FormCard',
    props: {
        title: {
            type: String,
            default: ''
        },
        form: {
            type: Object,
            default: () => ({ list: [{ uid: uniqueId() }] })
        },
        rules: {
            type: Object,
            default: () => ({})
        },
        listName: {
            type: String,
            default: 'list'
        },
        formItems: {
            type: Array,
            default: () => ([])
        },
        labelWidth: {
            type: String,
            default: '116px'
        }
    },
    data() {
        return {
            budgetMoney: null,
            cost: {},
            isError: []
        }
    },
    methods: {
        validMoney(planMoney, budgetMoney, index) {
            const res = planMoney > budgetMoney
            this.$set(this.isError, index, res)
        },
        handleBackfill(index, val, code) {
            if (!val) { return }
            const list = JSON.parse(JSON.stringify(this.form[this.listName]))
            // 作业范围jobAreaArr为前端自定义，后端需要的是jobArea
            if (code === 'jobAreaArr') {
                list[index]['jobArea'] = val.toString()
                console.log('aaaaa')
            } else {
                // 第2个options为费用的下拉
                const options = this.formItems[1]['options']
                options.some(item => {
                    if (item.value === val) {
                        this.cost = item
                    }
                })
                // budgetAmount预算量和budgetMoney预算金额回填
                list[index]['budgetAmount'] = this.cost.budgetAmount
                list[index]['budgetMoney'] = this.cost.budgetMoney
                // 后端需要basicFee、adjustmentFactor、arithmeticalUnit            
                list[index]['basicFee'] = this.cost.basicFee
                list[index]['adjustmentFactor'] = this.cost.adjustmentFactor
                list[index]['arithmeticalUnit'] = this.cost.arithmeticalUnit
            }
            
            this.$emit('update:form', { [this.listName]: list })
        },
        // 针对新建年度养护计划做的计算金额
        handleComputed(index, event) {
            if (!event) { return }
            let value = null
            // 通过workAmount工程量和unitPrice单价计算出计划完成金额
            const a = this.form[this.listName][index]['workAmount']
            const b = this.form[this.listName][index]['unitPrice']
            // 如果2个值任意一个没有则不处理
            if (!a || !b) {
                value = null
            } else {
                value = new BigNumber(a).times(b).toNumber()
            }
            const list = JSON.parse(JSON.stringify(this.form[this.listName]))
            list[index]['prepareCompletionMoney'] = value || null
            
            // 判断计划完成金额是否超出预算金额
            this.validMoney(value, list[index]['budgetMoney'], index)

            this.$emit('update:form', { [this.listName]: list })
        },
        accMultiply(num1, num2) {
            const num1Digits = (num1.toString().split('.')[1] || '').length
            const num2Digits = (num2.toString().split('.')[1] || '').length
            const baseNum = Math.pow(10, Math.max(num1Digits, num2Digits))
            return (Math.round(num1 * baseNum) * Math.round(num2 * baseNum)) / baseNum / baseNum
        },
        // 前端删除赔付项目列表
        handleDelete(index) {
            reconfirm({
                isPromise: false,
                callback: () => (this.deleteCard(index))
            })
        },
        deleteCard(index) {
            const list = JSON.parse(JSON.stringify(this.form[this.listName]))
            list.splice(index, 1)
            this.$emit('update:form', { [this.listName]: list })
        },
        // 前端新增赔付项目列表
        addCard() {
            const item = { budgetMoney: null, uid: uniqueId() }
            const list = JSON.parse(JSON.stringify(this.form[this.listName]))
            list.push(item)
            this.$emit('update:form', { [this.listName]: list })
        },
        handleValidate() {
            return new Promise((resolve) => {
                this.$refs['form'].validate(valida => {
                    const res = this.isError.some(item => item === true)
                    resolve(valida && !res)
                })
            })
        }
    },
}
</script>

<style lang="scss" scoped>
.el-form--inline.size-auto.width-100 {
    ::v-deep {
        // form的label-width：72px 根据实际label宽度修改
        .el-form-item__content {
            width: calc(100% - 116px);
        }
    }    
}
.margin-b-0 {
    margin-bottom: 0;
}
.add-box {
    width: 100%;
    height: 40px;
    line-height: 40px;
    margin-bottom: 24px;
    background: rgb(250, 250, 250);
    border: 1px solid #F5F7FA;
    border-radius: 5px;
    text-align: center;
    cursor: pointer;
    &:hover {
        background: rgb(240, 240, 240);
    }
    i {
        color: #171725;
        font-style: normal;
    }
}
</style>
